<?php
/**
 * Created by PhpStorm.
 * User: 王溪
 * Date: 2020/2/25
 * Time: 8:42
 */

namespace app\index\controller;


use think\Controller;

class Test extends Controller
{

    public function list1()
    {

       return $this->fetch('index');
    }

    function crabImage($imgUrl, $saveDir='./', $fileName=null){

        if(empty($imgUrl)){

            return false;

        }



        //获取图片信息大小

        $imgSize = getImageSize($imgUrl);

        if(!in_array($imgSize['mime'],array('image/jpg', 'image/gif', 'image/png', 'image/jpeg'),true)){

            return false;

        }

        //获取后缀名

        $_mime = explode('/', $imgSize['mime']);

        $_ext = '.'.end($_mime);



        if(empty($fileName)){  //生成唯一的文件名

            $fileName = uniqid(time(),true).$_ext;

        }

        //开始攫取

        ob_start();

        readfile($imgUrl);

        $imgInfo = ob_get_contents();

        ob_end_clean();

        if(!file_exists($saveDir)){

            mkdir($saveDir,0777,true);

        }

        $fp = fopen($saveDir.$fileName, 'a');

        $imgLen = strlen($imgInfo);    //计算图片源码大小

        $_inx = 1024;   //每次写入1k

        $_time = ceil($imgLen/$_inx);

        for($i=0; $i<$_time; $i++){

            fwrite($fp,substr($imgInfo, $i*$_inx, $_inx));

        }

        fclose($fp);

        return array('file_name'=>$fileName,'save_path'=>$saveDir.$fileName);

    }

    public function meizitu()
    {
        //首页

        $url = 'https://i.meizitu.net/thumbs/2019/04/176056_18a30_236.jpg';
        ob_start();
        readfile($url);
        $text=ob_get_contents();
        ob_end_clean();
        dump($text);die;
        $res = $this->crabImage('http://img0.imgtn.bdimg.com/it/u=844055886,878294880&fm=26&gp=0.jpg');
        dump($res);die;
        $home = file_get_contents('https://www.mzitu.com/');
        //匹配连接
//        $home_start = strpos($home,'<ul id="pins">');
//        $home_end = strpos($home,'</ul>',$home_start);
//        $list = substr($home,$home_start + strlen('<ul id="pins">'),$home_end - $home_start );
        $res_str = $this->meizitu_strpos($home,'<ul id="pins">','</ul>');
        $list = explode('<li>',$res_str);
        array_shift($list);
        foreach ($list as $k => $v){

        }

        //dump($list);die;

//        echo $home_start;
        dump($home);die;
    }
    public function meizitu_strpos($data, $tag1, $tag2)
    {
        $start = strpos($data, $tag1);
        $end = strpos($data, $tag2, $start);
        $res_str = substr($data,$start + strlen($tag1),$end - $start);
        return $res_str;
    }

    public function redis()
    {


        echo    cache('name',1);
    }

    public function qrcode()
    {
        $url = 'http://www.baidu.com';
        $qrcode = new QrCode($url);
        $qrcode->writeFile(  dirname(dirname(dirname(__DIR__))).'/public/static/qrcode/'.uniqid().'.png');
        echo 'end';
    }

    public function test_validate()
    {
        $data['name'] = '';
        $data['age'] = 'qq';
        //dump($data);die
        $validate = new \app\index\validate\Index();
        //dump($validate);die;
        if (!$validate->check($data)) {
            dump($validate->getError());
        }

    }


    /**
     * 测试常量
     */
    public function test_define(){
        echo Env::get('extend_path');
        echo '<br/>';
        $object = new test1();
        $object->test1();
        //Loader::import('test2',EXTEND_PATH);
        //  import

    }

    public function test_excel_old()
    {


        $data = db('user')->select();
        $headTitle = '测试表格导出';
        $headtitle = "<tr style='height:50px;border-style:none;><th border=\"0\" style='height:60px;width:270px;font-size:22px;' colspan='11' >{$headTitle}</th></tr>";;
        $titlename = "<tr> 
               <th style='width:70px;' >id</th>
               <th style='width:70px;' >姓名</th>
               <th style='width:70px;'>余额</th> 
               <th style='width:150px;'>性别</th> 
           </tr>";
        $filename = '测试名字';
        $this->excelData($data,$headtitle,$titlename,$filename.'.xls');
        dump($data);die;

    }
    /*
     *处理Excel导出
     *@param $datas array 设置表格数据
     *@param $titlename string 设置head表格标题
     *@param $title string 设置表头(行列表名)
     */

    public function excelData($datas,$titlename,$rowsname,$filename){

        $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>";

        $str .="<table  border=1><head>".$titlename."</head>";

        $str .= $rowsname;//列表名字

        foreach ($datas as $key=> $rt )
        {
            $str .= "<tr>";
            foreach ( $rt as $k => $v )
            {
                $str .= "<td>{$v}</td>";
            }
            $str .= "</tr>\n";
        }
        $str .= "</table></body></html>";

        header('Content-type: text/html; charset=utf-8');
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=test.xls");
        header('Cache-Control: max-age=0');


//        header( "Content-Type: application/vnd.ms-excel; name='excel'" );
//        header( "Content-type: application/octet-stream" );
//        header( "Content-Disposition: attachment; filename=".$filename );
//        header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
//        header( "Pragma: no-cache" );
//        header( "Expires: 0" );
        exit( $str );

    }





    public function hello($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }

    public function test_excel()
    {
        $data = db('user')->select();
        //dump($data);die;
        $this->assign('data',$data);

        return $this->fetch();

    }
    public function excel1()
    {
        echo 'laio';die;

    }


    public function excel()
    {
        $name='定制订单列表';
        $header=['id','名字','余额'];
        /*需要哪张表的数据就查询哪张表的数据*/
        $list = db('user')->select();
        $str = array();
        foreach ($list as $k => $v) {
            /*对应的数据库信息*/
            $str[] = [$v['id'],$v['name'],$v['money']];
        }
        $data = $str;
        //dump($data);die;
        $this->excelExport($name,$header,$data);
    }

    public function excelExport($fileName = '', $headArr = [], $data = []) {

        $fileName .= "_" . date("Y_m_d", time()) . "_".time().".xls";

        $objPHPExcel = new \PHPExcel();

        $objPHPExcel->getProperties();
//函数返回字符串中第一个字符的ASCII值。
        $key = ord("A"); // 设置表头
        //dump($key);die;

        foreach ($headArr as $v) {
//函数从指定的 ASCII 值返回字符。
            $colum = chr($key);
            //$objPHPExcel->getActiveSheet()->getColumnDimension($colum)->setWidth($key);设置宽度
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $key += 1;
        }

        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { // 行写入

            $span = ord("A");

            foreach ($rows as $keyName => $value) { // 列写入

                $objActSheet->setCellValue(chr($span) . $column, $value);

                $span++;

            }

            $column++;

        }

        $fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表

        $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表

        header('Content-Type: application/vnd.ms-excel');

        header("Content-Disposition: attachment;filename='$fileName'");

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        $objWriter->save('php://output'); // 文件通过浏览器下载

        exit();
    }
}